using UnityEngine;

namespace LS
{
    public class SerialIdGenerator
    {
        private int m_Min;
        private int m_Max;
        
        private int? m_SerialId;
        private int? m_Previous;
        private int m_Incremental;
        
        public int? Previous
        {
            get
            {
                return m_Previous;
            }
        }
        
        public int? Current
        {
            get
            {
                return m_SerialId;
            }
        }

        public int Next
        {
            get
            {
                if (m_SerialId.HasValue)
                {
                    return m_SerialId.Value + m_Incremental;
                }

                return m_Incremental < 0 ? m_Max : m_Min;
            }
        }

        public SerialIdGenerator(): this(0, int.MaxValue,1)
        {
            
        }
        
        public SerialIdGenerator(int min, int max, int incremental): this(min, max, null, incremental)
        {
            
        }
        
        public SerialIdGenerator(int min, int max, int? current, int incremental)
        {
            this.m_Min = min;
            this.m_Max = max;
            this.m_Incremental = incremental;
            this.m_SerialId = current;
        }
        
        public int Generate()
        {
            m_Previous = m_SerialId;
            int next = this.Next;
            if (next > m_Max)
            {
                next = m_Min;
            }
            else if(next < m_Min)
            {
                next = m_Max;
            }
            
            m_SerialId = next;
            return m_SerialId.Value;
        }
        
        public string SaveData()
        {
            string[] data = new string[5]
            {
                m_Min.ToString(),
                m_Max.ToString(),
                m_Incremental.ToString(),
                m_SerialId.HasValue? m_SerialId.Value.ToString(): string.Empty,
                m_Previous.HasValue? m_Previous.Value.ToString(): string.Empty,
            };
            return string.Join(",", data);
        }
        
        public void LoadData(string data)
        {
            string[] split = data.Split(",");
            m_Min = int.Parse(split[0]);
            m_Max = int.Parse(split[1]);
            m_Incremental = int.Parse(split[2]);
            m_SerialId = string.IsNullOrEmpty(split[3])? null: int.Parse(split[3]);
            m_Previous = string.IsNullOrEmpty(split[4])? null: int.Parse(split[4]);
        }
        
    }
}
